/**************************************************************************************************

	NSurvey - The web survey and form engine
	Copyright (c) 2004, Thomas Zumbrunn. (http://www.nsurvey.org)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

************************************************************************************************/


namespace Votations.NSurvey.WebAdmin.UserControls
{
	using System;
	using System.Web;
	using System.Web.UI;
	using System.Web.UI.WebControls;
	using System.Resources;
	using Microsoft.VisualBasic;
	using Votations.NSurvey;
	using Votations.NSurvey.Data;
	using Votations.NSurvey.DataAccess;
	using Votations.NSurvey.BusinessRules;
	using Votations.NSurvey.Web;

	/// <summary>
	/// Survey data CU methods
	/// </summary>
	public partial class SurveyOptionControl : UserControl
	{
		public event EventHandler OptionChanged;
		protected System.Web.UI.WebControls.DropDownList DropDownList1;
		protected System.Web.UI.WebControls.Literal PrivacySettingsTitle;
		protected System.Web.UI.WebControls.Literal RedirectionURLLabel;
		protected System.Web.UI.WebControls.TextBox RedirectionURLTextBox;
		protected System.Web.UI.WebControls.Literal ThanksMessageLabel;
		protected FreeTextBoxControls.FreeTextBox ThankYouFreeTextBox;
		protected SurveyListControl SurveyList;

		/// <summary>
		/// Id of the survey to edit
		/// if no id is given put the 
		/// usercontrol in creation mode
		/// </summary>
		public int SurveyId
		{
			get { return (ViewState["SurveyID"]==null) ? -1 : int.Parse(ViewState["SurveyID"].ToString()); }
			set { ViewState["SurveyID"] = value; }
		}


		protected void Page_Load(object sender, System.EventArgs e)
		{

			LocalizePage();
            //luyan add for resolving updatepanel error on download file using the Response.Write
            ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(ExportSurveyButton);
            ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(ImportXMLButton);
            

			MessageLabel.Visible = false;
			DeleteButton.Attributes.Add("onClick",
							"javascript:if(confirm('" +((PageBase)Page).GetPageResource("DeleteSurveyConfirmationMessage")+ "')== false) return false;");

			// Check if any survey has been assigned
			if (SurveyId == -1)
			{
				SwitchToCreationMode();
			}
			else
			{
				SwitchToEditionMode();
			}
		
		}

		private void LocalizePage()
		{
			SurveyInformationTitle.Text = ((PageBase)Page).GetPageResource("SurveyInformationTitle");
			SurveyTitleLabel.Text = ((PageBase)Page).GetPageResource("SurveyTitleLabel");
			OpeningDateLabel.Text = ((PageBase)Page).GetPageResource("OpeningDateLabel");
			DateForExampleInfo.Text = ((PageBase)Page).GetPageResource("DateForExampleInfo");
			CloseDateLabel.Text = ((PageBase)Page).GetPageResource("CloseDateLabel");
			ActiveSurveyLabel.Text = ((PageBase)Page).GetPageResource("ActiveSurveyLabel");
			ArchivedLabel.Text = ((PageBase)Page).GetPageResource("ArchivedLabel");
			CloneButton.Text = ((PageBase)Page).GetPageResource("CloneButton");
			ApplyChangesButton.Text = ((PageBase)Page).GetPageResource("ApplyChangesButton");
			DeleteButton.Text = ((PageBase)Page).GetPageResource("DeleteButton");
			CreateSurveyButton.Text = ((PageBase)Page).GetPageResource("CreateSurveyButton");
			EntryNotificationLabel.Text = ((PageBase)Page).GetPageResource("EntryNotificationLabel");
			ProgressDisplayLabel.Text = ((PageBase)Page).GetPageResource("ProgressDisplayLabel");
			EnableNavigationLabel.Text = ((PageBase)Page).GetPageResource("EnableNavigationLabel");
			EnableResumeLabel.Text = ((PageBase)Page).GetPageResource("EnableResumeLabel");
			NotificationSettingsTitle.Text = 	((PageBase)Page).GetPageResource("NotificationSettingsTitle");
			NotificationSubjectLabel.Text = ((PageBase)Page).GetPageResource("NotificationSubjectLabel");
			FromEmailNotificationLabel.Text = ((PageBase)Page).GetPageResource("FromEmailNotificationLabel");
			ToEmailNotificationLabel.Text = ((PageBase)Page).GetPageResource("ToEmailNotificationLabel");
			ScoredLabel.Text = ((PageBase)Page).GetPageResource("ScoredLabel");
			ExportSurveyButton.Text = ((PageBase)Page).GetPageResource("ExportSurveyButton");
			ImportSurveyTitle.Text = ((PageBase)Page).GetPageResource("ImportSurveyTitle");
			ImportXMLButton.Text = ((PageBase)Page).GetPageResource("ImportXMLButton");
			DisableQuestionNumbering.Text = ((PageBase)Page).GetPageResource("DisableQuestionNumbering");
		}

		/// <summary>
		/// Setup the control in creation mode
		/// </summary>
		private void SwitchToCreationMode()
		{
			// Creation mode
			SurveyImportPlaceHolder.Visible = 
				((PageBase)Page).CheckRight(NSurveyRights.AllowXmlImport, false);
			CreateSurveyButton.Visible = true;
			ApplyChangesButton.Visible = false;
			DeleteButton.Visible = false;
			CloneButton.Visible = false;
			ExportSurveyButton.Visible = false;
			EditUi.Visible = false;
			SurveyList.Visible = false;
		}

		/// <summary>
		/// Setup the control in edition mode
		/// </summary>
		private void SwitchToEditionMode()
		{
			ExportSurveyButton.Visible = ((PageBase)Page).CheckRight(Votations.NSurvey.Data.NSurveyRights.ExportSurveyXml, false);
			CreateSurveyButton.Visible = false;
			ApplyChangesButton.Visible = ((PageBase)Page).CheckRight(Votations.NSurvey.Data.NSurveyRights.ApplySurveySettings, false);
			DeleteButton.Visible = ((PageBase)Page).CheckRight(Votations.NSurvey.Data.NSurveyRights.DeleteSurvey, false);
			CloneButton.Visible = ((PageBase)Page).CheckRight(Votations.NSurvey.Data.NSurveyRights.CloneSurvey, false);
			SurveyImportPlaceHolder.Visible = false;

			EditUi.Visible = true;
			SurveyList.Visible = true;
			if (!IsPostBack)
			{
				BindFields();
			}
		}

		/// <summary>
		/// Get the current DB data and fill 
		/// the fields with them
		/// </summary>
		private void BindFields()
		{
			SurveyList.SurveyId = SurveyId;
			SurveyList.BindDropDown();

			DateFormatLabel.Text = (DateTime.Now).ToShortDateString();

			// Retrieve the survey data
			SurveyData surveyData = new Surveys().GetSurveyById(SurveyId);
			SurveyData.SurveysRow survey = surveyData.Surveys[0];

			// Assigns the retrieved data to the correct fields
			TitleTextBox.Text = survey.Title;
			ActiveCheckBox.Checked  = survey.Activated;
			ArchiveCheckBox.Checked = survey.Archive;
			ScoredCheckbox.Checked = survey.Scored;
			QuestionNumberingCheckbox.Checked = survey.QuestionNumberingDisabled;
			OpeningDateTextBox.Text = survey.IsOpenDateNull() ? null : survey.OpenDate.ToShortDateString();
			CloseDateTextbox.Text = survey.IsCloseDateNull() ? null : survey.CloseDate.ToShortDateString();
			EnableNavigationCheckbox.Checked = survey.NavigationEnabled;
			EmailFromTextbox.Text = survey.EmailFrom;
			EmailToTextBox.Text = survey.EmailTo;
			EmailSubjectTextbox.Text = survey.EmailSubject;

	
			EntryNotificationDropdownlist.DataSource = new Surveys().GetSurveyNotificationModes();
			EntryNotificationDropdownlist.DataTextField = "description";
			EntryNotificationDropdownlist.DataValueField = "NotificationModeId";

			EntryNotificationDropdownlist.DataBind();
			((PageBase)Page).TranslateListControl(EntryNotificationDropdownlist);
			EntryNotificationDropdownlist.SelectedValue = survey.NotificationModeID.ToString();

			if ((NotificationMode)survey.NotificationModeID != 
				NotificationMode.None)
			{
				NotificationPlaceHolder.Visible = true;
			}
			else
			{
				NotificationPlaceHolder.Visible = false;
			}

			ProgressDisplayDropDownList.DataSource = new Surveys().GetSurveyProgressModes();
			ProgressDisplayDropDownList.DataTextField = "description";
			ProgressDisplayDropDownList.DataValueField = "ProgressDisplayModeId";
			ProgressDisplayDropDownList.DataBind();
			((PageBase)Page).TranslateListControl(ProgressDisplayDropDownList);
			ProgressDisplayDropDownList.SelectedValue = survey.ProgressDisplayModeID.ToString();
		
			ResumeModeDropdownlist.DataSource = new Surveys().GetSurveyResumeModes();
			ResumeModeDropdownlist.DataTextField = "description";
			ResumeModeDropdownlist.DataValueField = "ResumeModeId";
			ResumeModeDropdownlist.DataBind();
			((PageBase)Page).TranslateListControl(ResumeModeDropdownlist);
			ResumeModeDropdownlist.SelectedValue = survey.ResumeModeID.ToString();
		}


		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{

		}
		#endregion

		protected void EntryNotificationDropdownlist_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if ((NotificationMode)int.Parse(EntryNotificationDropdownlist.SelectedValue) != 
				NotificationMode.None)
			{
				NotificationPlaceHolder.Visible = true;
			}
			else
			{
				NotificationPlaceHolder.Visible = false;
			}
		}


		/// <summary>
		/// Apply the survey data changes to the DB
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void ApplyChangesButton_Click(object sender, System.EventArgs e)
		{
			if (OpeningDateTextBox.Text.Length != 0 && 
				!Information.IsDate(OpeningDateTextBox.Text))
			{
				MessageLabel.Text = ((PageBase)Page).GetPageResource("InvalidOpeningDate");
				MessageLabel.Visible = true;
				return;
			}

			if (CloseDateTextbox.Text.Length != 0 && 
				!Information.IsDate(CloseDateTextbox.Text))
			{
				MessageLabel.Text = ((PageBase)Page).GetPageResource("InvalidClosingDate");
				MessageLabel.Visible = true;
				return;
			}

			if (((NotificationMode)int.Parse(EntryNotificationDropdownlist.SelectedValue)) != 
				NotificationMode.None)
			{
				if (EmailFromTextbox.Text.Length == 0 || !((PageBase)Page).isEmail(EmailFromTextbox.Text) )
				{
					MessageLabel.Text = ((PageBase)Page).GetPageResource("InvalidFromEmail");
					MessageLabel.Visible = true;
					return;
				}

				if (EmailToTextBox.Text.Length == 0 || !((PageBase)Page).isEmail(EmailToTextBox.Text))
				{
					MessageLabel.Text = ((PageBase)Page).GetPageResource("InvalidToEmail");
					MessageLabel.Visible = true;
					return;
				}
				NotificationPlaceHolder.Visible = true;
			}
			else
			{
				EmailFromTextbox.Text = string.Empty;
				EmailToTextBox.Text = string.Empty;
				EmailSubjectTextbox.Text = string.Empty;
				NotificationPlaceHolder.Visible = false;
			}

			// Creates a new entity and assign
			// the updated values
			SurveyData surveyData = new SurveyData();
			SurveyData.SurveysRow surveyRow = surveyData.Surveys.NewSurveysRow();
			surveyRow.SurveyId = SurveyId;
			surveyRow.Title = TitleTextBox.Text;
			surveyRow.Activated = ActiveCheckBox.Checked;
			surveyRow.Archive = ArchiveCheckBox.Checked;
			surveyRow.Scored = ScoredCheckbox.Checked;
			surveyRow.QuestionNumberingDisabled = QuestionNumberingCheckbox.Checked;
			surveyRow.NavigationEnabled = EnableNavigationCheckbox.Checked;
			surveyRow.ResumeModeID = int.Parse(ResumeModeDropdownlist.SelectedValue);
			surveyRow.ProgressDisplayModeID = int.Parse(ProgressDisplayDropDownList.SelectedValue);
			surveyRow.NotificationModeID = int.Parse(EntryNotificationDropdownlist.SelectedValue);
			if (((NotificationMode)surveyRow.NotificationModeID) != 
				NotificationMode.None)
			{
				surveyRow.EmailFrom = EmailFromTextbox.Text;
				surveyRow.EmailTo = EmailToTextBox.Text;
				surveyRow.EmailSubject = EmailSubjectTextbox.Text;
			}

			if (OpeningDateTextBox.Text.Length != 0)
			{
				surveyRow.OpenDate = DateTime.Parse(OpeningDateTextBox.Text);
			}
			if (CloseDateTextbox.Text.Length != 0)
			{
				surveyRow.CloseDate = DateTime.Parse(CloseDateTextbox.Text);
			}
			surveyData.Surveys.AddSurveysRow(surveyRow);

			// Update the DB
			new Survey().UpdateSurvey(surveyData);

			MessageLabel.Text = ((PageBase)Page).GetPageResource("SurveyUpdatedMessage");
			MessageLabel.Visible = true;

			
			
			// Let the subscribers know that something changed
			OnOptionChanged();
		}

		protected void CreateSurveyButton_Click(object sender, System.EventArgs e)
		{
			// Creates a new entity and assign
			// the new values
			SurveyData surveyData = new SurveyData();
			SurveyData.SurveysRow surveyRow = surveyData.Surveys.NewSurveysRow();
			surveyRow.Title = TitleTextBox.Text;
			surveyRow.Activated = false;
			surveyRow.Archive = false;
			surveyRow.AccessPassword = string.Empty;
			surveyRow.SurveyDisplayTimes = 0;
			surveyRow.ResultsDisplayTimes = 0;
			surveyRow.SetOpenDateNull();
			surveyRow.SetCloseDateNull();
			surveyRow.CreationDate = DateTime.Now;
			surveyRow.IPExpires = 1440;
			surveyRow.CookieExpires = 1440;
			surveyRow.OnlyInvited = false;
			surveyRow.Scored = false;
			surveyRow.QuestionNumberingDisabled = false;
			surveyRow.ProgressDisplayModeID = (int)ProgressDisplayMode.PagerNumbers;
			surveyRow.ResumeModeID = (int)ResumeMode.NotAllowed;
			surveyData.Surveys.AddSurveysRow(surveyRow);

			try
			{
				// Add the survey in the DB
				new Survey().AddSurvey(surveyData);
				AssignSurveyToUser(surveyData.Surveys[0].SurveyId);
				UINavigator.NavigateToSurveyBuilder(surveyRow.SurveyId, 4);
			}
			catch (SurveyExistsFoundException ex)
			{
				MessageLabel.Text =  ex.Message;
				MessageLabel.Visible = true;
			}
		}

		/// <summary>
		/// If a valid user is logged in assign the survey 
		/// to his account
		/// </summary>
		private void AssignSurveyToUser(int surveyId)
		{
			// Can we assign the survey to the current user
			if (!((PageBase)Page).IsSingleUserMode(false))
			{
				new Survey().AssignUserToSurvey(surveyId, 
					((PageBase)Page).NSurveyUser.Identity.UserId);
			}
		}
		
		protected void DeleteButton_Click(object sender, System.EventArgs e)
		{
			// Delete survey from the DB
			new Survey().DeleteSurveyById(SurveyId);
			MessageLabel.Text = ((PageBase)Page).GetPageResource("SurveyDeletedMessage");

			MessageLabel.Visible = true;

			UINavigator.NavigateToSurveyOptions(-1, ((PageBase)Page).MenuIndex);
		}

		protected void OnOptionChanged()
		{
			if (OptionChanged != null)
			{
				OptionChanged(this, EventArgs.Empty);
			}
		}

		protected void CloneButton_Click(object sender, System.EventArgs e)
		{
			SurveyData clonedSurvey = new Survey().CloneSurvey(SurveyId);

            //Retrieve the new survey ID
			SurveyId = clonedSurvey.Surveys[0].SurveyId;
		
			// Update the form fields
			BindFields();

			// Let the subscribers know that something has changed
			OnOptionChanged();
		}

		protected void ExportSurveyButton_Click(object sender, System.EventArgs e)
		{
			Response.Charset = "utf-8";
			Response.ContentType = "application/octet-stream";
			
			//Response.ContentType = "text/xml";
			Response.AddHeader("Content-Disposition", "attachment; filename=\"nsurvey_survey"+SurveyId+".xml\"");
		
			NSurveyForm surveyForm = new Surveys().GetFormForExport(SurveyId);
			surveyForm.WriteXml(Response.OutputStream, System.Data.XmlWriteMode.IgnoreSchema);

			Response.End();
		}

		protected void ImportXMLButton_Click(object sender, System.EventArgs e)
		{
			if (ImportFile.PostedFile != null)
			{
				NSurveyForm importedSurveys = new NSurveyForm();
				try
				{
					importedSurveys.ReadXml(ImportFile.PostedFile.InputStream);
					if (importedSurveys.Survey.Rows.Count > 0)
					{
						new Survey().ImportSurveys(importedSurveys, ((PageBase)Page).NSurveyUser.Identity.UserId);
						AssignSurveyToUser(importedSurveys.Survey[0].SurveyID);
						UINavigator.NavigateToSurveyBuilder(importedSurveys.Survey[0].SurveyID, 4);
					}
				}
				catch (Exception ex)
				{
					MessageLabel.Text = ex.Message;
					MessageLabel.Visible = true;
				}
			}
		}
	}
}
